package ee.project;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class SimilarityJoin {

	private List<List<Record>> naivePair(List<Record> recordSet,
			double threshold) {
		List<List<Record>> resultSet = new LinkedList<List<Record>>();
		double similarity;
		for (int i = 1; i < recordSet.size(); i++) {
			Record r1 = recordSet.get(i);
			for (int j = 0; j < i; j++) {
				Record r2 = recordSet.get(j);
				similarity = JaccardSimilarity(overlap(r1, r2), r1
						.getRecordLength(), r2.getRecordLength());
				if (similarity >= threshold) {
					resultSet.add(new ArrayList<Record>(Arrays.asList(r1, r2)));
				}
			}
		}

		return resultSet;
	}

	private int overlap(Record r1, Record r2) {
		int overlap = 0;
		int i = 0, j = 0;
		while (i <= r1.getRecordLength() && j <= r2.getRecordLength()) {
			if (r1.getToken(i) == r2.getToken(j)) {
				overlap++;
				i++;
				j++;
			} else {
				if (r1.getToken(i) < r2.getToken(j)) {
					i++;
				} else {
					j++;
				}
			}
		}
		return overlap;
	}

	private double JaccardSimilarity(int overlap, int r1Length, int r2Length) {
		return (overlap) / (r1Length + r2Length - overlap);
	}
}
